package com.jse.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import com.jse.Io;
import com.jse.Lang;
import com.jse.Log;
import com.jse.json.Json;
import com.jse.json.JsonObject;
import com.jse.json.XML;
import com.jse.multipart.MultipartFormData;
import com.sun.net.httpserver.HttpExchange;

public class Tbl implements Map<String,Object> {

	private String method;
	private String path;
	private String suffix;
	private Map<String,HttpCookie> cookies;
	private HttpExchange ex;
	private String serverName;
	private JsonObject tbl;
	
	public Tbl(HttpExchange ex) {
		this.ex=ex;
		method=ex.getRequestMethod();
		path=ex.getRequestURI().getPath();
		int suffixindex=path.lastIndexOf(".");
		suffix=suffixindex==-1?path:path.substring(suffixindex+1);
		serverName=ex.getLocalAddress().getHostName();
//		parseTbl(ex);
		Log.get("jseservlet").debug("-http {}:{}",method,path);
	}
	
	public Map<String,HttpCookie> getCookies(){if(cookies==null)cookies=Web.cookies(ex);return cookies;}
	public String sessionId() {var ck=getCookies().get("JSESSIONID");return ck==null?null:ck.getValue();}
	public HttpSession session(){return session(true);}
	public HttpSession session(boolean isnew){
		String sid=sessionId();
		if(sid==null||sid.isEmpty()){sid=Lang.snowflake()+"";}
		if(Web.SESSIONS.containsKey(sid))return Web.SESSIONS.get(sid);
		HttpSession httpSession = new HttpSession(sid);
		Web.SESSIONS.put(sid,httpSession);
		return httpSession;
	}
	
	
	
	public void setAttribute(String n,Object v) {ex.setAttribute(n, v);}
	public Object getAttribute(String n) {return ex.getAttribute(n);}
	
	@Override public int size() {return tbl().size();}
	@Override public boolean isEmpty() {return tbl().isEmpty();}
	@Override public boolean containsKey(Object key) {return tbl().containsKey(key);}
	@Override public boolean containsValue(Object value) {return tbl().containsValue(value);}
	@Override public Object get(Object key) {return tbl().get(key);}
	@Override public Object put(String key, Object value) {return tbl().put(key, value);}
	@Override public Object remove(Object key) {return tbl().remove(key);}
	@Override public void putAll(Map<? extends String, ? extends Object> m) {tbl().putAll(m);}
	@Override public void clear() {tbl().clear();}
	@Override public Set<String> keySet() {return tbl().keySet();}
	@Override public Collection<Object> values() {return tbl().values();}
	@Override public Set<Entry<String, Object>> entrySet() {return tbl().entrySet();}
	@Override public String toString() {return Json.toJson(this);}
	
	private void parseTbl(HttpExchange ex) {
		if("GET".equals(method)) {
			if(ex.getRequestURI().getQuery()== null) {return;}
	        final String[] items = ex.getRequestURI().getQuery().split("&");
	        Arrays.stream(items).forEach(t ->{
	            final String[] v = t.split("=");
	            if( v.length == 2) {
	                try{
	                    final String key = URLDecoder.decode(v[0],"utf8");
	                    final String val = URLDecoder.decode(v[1],"utf8");
	                    tbl.add(key,val);
	                }catch (UnsupportedEncodingException e) {}
	            }
	        });
		}else if("POST".equals(method)) {
        	String reqcontentType=ex.getRequestHeaders().getFirst("Content-Type");
        	if(reqcontentType==null) {//没有body none
        	}else if(reqcontentType.startsWith("application/x-www-form-urlencoded")) {
        		tbl.putAll(new JsonObject(Io.readString(ex.getRequestBody())));
            }else if(reqcontentType.startsWith("application/json")) {
            	tbl.putAll(Json.jsonObject(Io.readString(ex.getRequestBody())));
            }else if(reqcontentType.startsWith("application/xml")) {
            	tbl.putAll(XML.toJSONObject(Io.readString(ex.getRequestBody())));
            }else if(reqcontentType.startsWith("multipart/form-data")) {//上传
            	try {
            		MultipartFormData formData = new MultipartFormData();
                	formData.parseRequestStream(ex.getRequestBody(),StandardCharsets.UTF_8);
                	System.out.println(formData.getParamListMap());
                	System.out.println(formData.getFileListValueMap());
                	formData.getFile("fx").write("d:/1.png");
				} catch (IOException e) {
				}
            }else {
            	tbl.put("body",Io.readString(ex.getRequestBody()));
            }
        }
	}
	public String getPath() {return path;}
	public String getSuffix() {return suffix;}
	public JsonObject tbl() {
		if(tbl!=null)return tbl;
		tbl=new JsonObject();
		parseTbl(ex);
		return tbl;
	}

	public String getServerName() {return serverName;}
	
	
}
